<template>
  <el-dialog v-model="dialogVisible" title="修改密码" width="500px" :destroy-on-close="true" draggable>
    <el-form ref="ruleFormRef" :model="passwordForm" label-width="80px" :rules="rules">
      <el-form-item label="新密码" prop="newPassword">
        <el-input type="password" v-model="passwordForm.newPassword"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElNotification, FormInstance } from "element-plus";
import { updatePassword } from "@/api/modules/user";
import { User } from "@/api/interface";
import { useRouter } from "vue-router";
import { LOGIN_URL } from "@/config";
import { useUserStore } from "@/stores/modules/user";

interface PasswordForm {
  oldPassword: string;
  newPassword: string;
  confirmPassword: string;
}

const validateConfirmPassword = (rule: any, value: string, callback: Function) => {
  if (value === passwordForm.value.newPassword) {
    callback();
  } else {
    callback(new Error("两次输入的密码不一致"));
  }
};
const rules = {
  newPassword: [
    { required: true, message: "请输入新密码" },
    { min: 6, message: "密码长度至少为6位" }
  ],
  confirmPassword: [{ required: true, message: "请再次输入新密码" }, { validator: validateConfirmPassword }]
};

const cancel = () => {
  dialogVisible.value = false;
  // 重置表单
  passwordForm.value = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
  };
};

const reqUpdatePassword = ref<User.ReqUpdatePassword>({
  password: ""
});

const router = useRouter();
const userStore = useUserStore();

const changePassword = async () => {
  console.log(passwordForm.value);
  // 执行修改密码逻辑
  reqUpdatePassword.value!.password = passwordForm.value.newPassword;
  const data = await updatePassword(reqUpdatePassword.value);
  if (data.code == "200") {
    ElNotification({ title: "修改密码", message: data.msg + "请重新登录", type: "success" });

    // 清除 Token
    userStore.setToken("");

    // 重定向到登陆页
    router.replace(LOGIN_URL);
  }
  dialogVisible.value = false;
  // 清空表单
  passwordForm.value = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: ""
  };
};

const ruleFormRef = ref<FormInstance>();
const submit = () => {
  ruleFormRef.value!.validate((valid: boolean) => {
    if (valid) {
      // 表单验证通过，执行修改密码逻辑
      changePassword();
    }
  });
};

const dialogVisible = ref(false);
const passwordForm = ref<PasswordForm>({
  oldPassword: "",
  newPassword: "",
  confirmPassword: ""
});

const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });
</script>
